<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;

require_once './lib/function.inc.php';
require_once './lib/AopSdk.php';
require_once './lib/HttpRequst.php';
require_once './lib/UserInfo.php';
require_once './lib/PushMsg.php';
require_once './lib/config.php';
require_once './lib/MysqliDb.php';

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class IndexController extends HomeController {

    //系统首页
    public function index(){
       /* //客户端信息
        $user_agent = $_SERVER['HTTP_USER_AGENT'];

        $user=session('user');
        $auth_code=  \HttpRequest::getRequest ( "auth_code" );

        if(!stristr($user_agent,"AlipayClient") || !stristr($user_agent,"AlipayDefined")){
            header('Location:http://m.taobao.com'); // 不包含肯定不是支付宝访问的所以跳转网址吧
        }

        $config=C('ALI');
        if (!isset($user) && empty ( $auth_code )){ // 这里判断session不含有跳转到授权链接
            $ru= "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=".$config['app_id']."&scope=auth_userinfo&redirect_uri=".urlencode($config['url']);
            session("user",null);
            header('Location:'.$ru);
        }

        if(!empty($user)){
            $results =M('agent')->where (array('ali_user_id'=>$user['ali_user_id']))->find();
            session('user',$results);
        }

        if(! empty ( $auth_code ) && empty($results)){
            //获取用户资料并存库
            $userinfo = new \UserInfo ();
            $user_info_resp=$userinfo->getUserInfo ( $auth_code );

            $data=Array(
                "user_id" => $user_info_resp->user_id,
                "avatar" => $user_info_resp->avatar,
                "nick_name" => !empty($user_info_resp->nick_name)?$user_info_resp->nick_name:'',
                "is_certified" => !empty($user_info_resp->is_certified)?$user_info_resp->is_certified:'',
                "user_status" => !empty($user_info_resp->user_status)?$user_info_resp->user_status:'',
                "create_time"=>time()
            );

            if(!empty($user_info_resp->user_id)){
                $ali_user_id=$user_info_resp->user_id;
                $re =M('agent')->where (array('ali_user_id'=>$ali_user_id))->find();
                if(empty($re)){
                    M('agent')->add($data);
                }
            }
        }*/

        header ( "Content-type: text/html; charset=utf-8" );
        $config=M('config')->where(array('name'=>'RED_STAR_TIME'))->find();
        $red=M('red_envelopes')->where(array('type'=>1,'status'=>1))->find();
        if(empty($results)){ // 没找到订单返回错误信息
          echo "没有红包可以领取";
          die();
        }

        $this->assign('config',$config);
        $this->assign('red',$red);
        $this->display();
    }



    public function trigger(){
        $config=C('ALI');
        $user=session('user');
       
        $crowd_no=I('post.crowd_no');

        if(empty($crowd_no)){ // 没找到订单返回错误信息
            $data = array('msg' =>'缺少订单号' ,'code' =>'100' );
            $this->ajaxReturn($data);
        }

        //红包信息
        $red=M('red_envelopes')->where(array('crowd_no'=>$crowd_no))->find();

        if (empty($user)){
            $data = array('msg' =>'参数错误' ,'code' =>'101' );
            $this->ajaxReturn($data);
        }

       $user2=M('agent')->where(array('ali_user_id'=>$user['ali_user_id']))->find(); 
       if (empty($user2)) {
        // 没有用户信息怎么可能分享红包的防止作弊
         $data = array('msg' =>'参数错误' ,'code' =>'102' );
         $this->ajaxReturn($data);
       }

        //查看用户是否领取
       $red_user=M('envelopes_agent')->where(array('crowd_no'=>$crowd_no,'uid'=>$user['id']))->find();
       if(!empty($red_user)){
          $this->ajaxReturn(['msg' =>'不能重复领取' ,'code' =>'103' ]);
       }

       //领取红包的人数
       $count=M('envelopes_agent')->where(array('crowd_no'=>$crowd_no))->count();

       if($count>=$red['num']){
          $this->ajaxReturn(['msg' =>'红包数量领取完了' ,'code' =>'104' ]);
       }

       $aop = new \AopClient ();
       $aop->gatewayUrl = $config['gatewayUrl'];
       $aop->appId = $config['app_id'];
       $aop->rsaPrivateKey = $config['merchant_private_key'];
       $aop->alipayrsaPublicKey=$config['alipay_public_key'];
       $aop->apiVersion = '1.0';
       $aop->signType = $config['sign_type'];
       $aop->postCharset='utf-8';
       $aop->format='json';
       $request = new \AlipayMarketingCampaignCashTriggerRequest ();
       $request->setBizContent("{" .
       "\"user_id\":\"".$user['ali_user_id']."\"," .
       "\"crowd_no\":\"".$crowd_no."\"," .
       "  }");
       $result = $aop->execute ( $request); 

       $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
       $resultCode = $result->$responseNode->code;

       $trigger_result= $result->$responseNode->trigger_result; 
       if(!empty($resultCode)&&$resultCode == 10000){
         if($trigger_result){
           //存入数据库
            $t=time();
            $data = array(
              'uid'=>$user['id'],
              'money' => $result->$responseNode->prize_amount, 
              'biz_no'=>$result->$responseNode->biz_no,
              'time'=>$t,
              'num'=>1,
              'crowd_no'=>$crowd_no
            );
           
            $row=M('envelopes_agent')->add($data);
            if($row){
               $this->ajaxReturn(['msg' =>"服务器出错" ,'code' =>'1','money'=>$result->$responseNode->prize_amount]);
            }else{
              $this->ajaxReturn(['msg' =>"服务器出错" ,'code' =>'105' ]);
            }
         } 

       }else{
         $this->ajaxReturn(['msg' =>$result->$responseNode->sub_msg ,'code' =>'106' ]);
       }


    }



}